package com.ellricky.baselib.util;

import android.app.Activity;

import com.andr.common.http.callback.GsonRespParser;
import com.andr.common.util.ToastUtil;
import com.ellricky.baselib.http.entity.EDataEntiy;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class NewEntityCallback<T> extends NewEBaseCallback {
    private Class mClazz;

    public NewEntityCallback(Activity context) {
        this(context, true);
    }

    public NewEntityCallback(Activity context, boolean showLoading) {
        this(context, showLoading, "");
    }

    public NewEntityCallback(Activity context, boolean showLoading, String loadMsg) {
        super(context, showLoading, loadMsg);
        Type genType = this.getClass().getGenericSuperclass();
        if (genType != null) {
            Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
            this.mClazz = (Class) params[0];
        }
    }


    @Override
    public int dataFlag() {
        return 1;
    }

    @Override
    public void parseDataJO(String code, String msg, JSONObject dataJO) {
        super.parseDataJO(code, msg, dataJO);
        try {
            T entity = this.parseJsonObject(dataJO);
            if (entity != null) {
                if ("1".equals(code)) {
                    this.onSuccess(entity, msg);
                } else {
                    this.onErrorCode(entity, code, msg);
                }
            } else {
                this.onErrorCode(null, "-1001", "解析错误");
            }
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    public abstract void onSuccess(T var1, String var2);

    public void onErrorCode(T data, String code, String msg) {
        ToastUtil.show(this.getMContext(), msg);
    }

    private T parseJsonObject(JSONObject response) {
        T entity = null;
        if (this.mClazz != null) {
            Type gsonType = new GsonRespParser(EDataEntiy.class, new Class[]{mClazz});
            EDataEntiy eDataEntiy = (new Gson()).fromJson(response.toString(), gsonType);
            entity = (T) eDataEntiy.getData();
        }
        return entity;
    }
}
